/*
 * BAAES256.java
 * classes : com.qim.basdk.utilites.encrypt.BAAES256
 * @author xuwei
 * V 1.0.0
 * Created at 2016年4月15日 上午9:54:14
 */
package com.langsheng.lsintell.utils.encrypt;

import android.util.Base64;

import com.langsheng.lsintell.utils.LSConst;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES256数据加密
 *
 * @author xuwei
 *         <p>
 *         created at 2016年4月15日 上午9:54:14
 */
public class LSAES256 {

    /**
     * 加密
     */
    public final static int MODE_ENCRYPT = Cipher.ENCRYPT_MODE;
    /**
     * 解密
     */
    public final static int MODE_DECRYPT = Cipher.DECRYPT_MODE;

    /**
     * 仅用于给用户密码加密
     *
     * @param pwd
     * @return
     */
    public static String encryptPwd(String pwd) {
        if (pwd == null) {
            pwd = "";
        }
        byte[] bPwd;
        try {
            bPwd = pwd.getBytes(LSConst.CHARSET_UTF8);
        } catch (Exception e) {
            bPwd = pwd.getBytes();
        }
        try {
            return Base64.encodeToString(encrypt(bPwd, LSEncryptUtil.KEY, MODE_ENCRYPT), Base64.DEFAULT);
        } catch (Exception e) {
        }
        return pwd;
    }

    public static byte[] decryptPwd(String src) throws Exception {
        byte[] aesSrc = Base64.decode(src, Base64.DEFAULT);
        return encrypt(aesSrc, LSEncryptUtil.KEY, MODE_DECRYPT);
    }

    public static byte[] encrypt(byte[] src, byte[] pwd, int mode) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(pwd, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
        cipher.init(mode, skeySpec);
        byte[] mid;
        if (mode == MODE_ENCRYPT) {
            mid = paddingData(src);
        } else {
            mid = src;
        }
        return cipher.doFinal(mid);
    }

    /**
     * 补齐的16位的整数倍
     *
     * @param bytes
     * @return
     */

    private static byte[] paddingData(byte[] bytes) {

        int length = bytes.length / 16;
        if (length * 16 < bytes.length) {
            length++;
        }

        byte[] result = new byte[length * 16];
        System.arraycopy(bytes, 0, result, 0, bytes.length);
        for (int i = bytes.length; i < result.length; i++) {
            result[i] = 0x00;
        }
        return result;
    }

}
